package machine.scheduled;

import cn.hutool.core.date.DateUtil;
import machine.api.TencentApi;
import machine.bean.Person;
import machine.bean.Tencent;
import machine.send.service.SendService;
import machine.utils.CacheUtils;
import machine.utils.GroupUtils;
import machine.utils.StatisticalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author zhanghui145
 * @date 2021/12/26 15:48
 * @since 1.0.0
 */
@Service
public class ScheduledServiceImpl {

    // 这里修改自己的QQ号
    private static final Integer MY_QQ = 1111111111;

    @Autowired
    private TencentApi tencentApi;

    @Autowired
    private SendService sendService;

    @Autowired
    private CacheUtils cacheUtils;

    private static final Executor executor = Executors.newFixedThreadPool(2);

    @Scheduled(cron = "0 58 23 * * ?")
    public void sendCountMsg() {
        try {
            List<Person> persons = StatisticalUtil.getSort();
            persons.stream().filter(p -> Objects.isNull(p.getName()) || "".equals(p.getName()))
                    .forEach(p -> {
                        Tencent tencent = tencentApi.getByQQ(p.getQq());
                        p.setName(tencent.getName());
                    });
            sendService.sendGroupMsg(GroupUtils.friendGroup(), countMsg(persons));
        } catch (Exception e) {
            sendService.sendPrivateMsg(MY_QQ, "定时发生错误，" + e.getMessage());
        } finally {
            sendService.sendPrivateMsg(MY_QQ, "定时任务完成。");
            StatisticalUtil.clear();
        }
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void clearChatId() {
        executor.execute(()->cacheUtils.expireClear());
    }

    private String countMsg(List<Person> persons) {
        StringBuilder sb = new StringBuilder();
        String date = DateUtil.today();
        sb.append(date).append("今日发言统计：");
        if (persons.isEmpty()) {
            return sb.append("无").toString();
        }
        sb.append("\n").append("划水王：").append(persons.get(0).getName());
        for (int i = 0; i < persons.size(); i++) {
            sb.append("\n").append("No").append((i + 1)).append("， ").append(persons.get(i).getName())
                    .append("， ").append(persons.get(i).getCounts()).append("条。");
        }
        return sb.toString();
    }
}
